//
//  RootMakeSureTheOrderViewController.m
//  BaseFrame
//
//  Created by 吕金状 on 2017/8/9.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "RootMakeSureTheOrderViewController.h"
#import "RootMakeSureTheOrderTableViewCell.h"
#import "MethodOfPaymentView.h"
#import "TheMembershipCardToPayView.h"
#import "LackOfBalanceView.h"
#import "MemberPrepaidPhoneViewController.h"

@interface RootMakeSureTheOrderViewController ()<UITableViewDelegate , UITableViewDataSource , UITextViewDelegate>
{
    NSString *promptStrong;
    NSString *loId;//订单号
    NSString *payType; //支付方式 :0-会员卡支付,1-支付宝支付,2-微信支付
}
Strong UIView *headView;
Strong UITableView *tableView;
Strong UIView *footView;
Strong NSMutableArray *dataArray; /**<*/
Strong UILabel *theOrderNumberLabel; // 订单编号
Strong UITextView *textView;
Strong UILabel *moneyLabel; //总金额
Strong UIButton *paymentButton; /**<*/

//支付宝支付-微信支付
- (void)payByALiWithHandle:(NSString *)orderString;
- (void)weiXinpay:(NSDictionary *)dic;

@end

//网络
@implementation RootMakeSureTheOrderViewController(NetWorking)

//订单支付
- (void)payOrder{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"loId":loId,
                                 @"payType":payType,
                                 @"oType":@"1",
                                 @"content":self.textView.text,
                                 @"fromType":@"1"
                                 };
    [[AFAppDotNetAPIClient sharedClient] POST:@"wardrobe/Laundry_Order/payOrder.do" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            if ([payType isEqualToString:@"0"]) {
                //会员卡支付
                //ShowMessage(@"支付完成");
                [self.view makeToast:responseObject[@"msg"] duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                
            }else if ([payType isEqualToString:@"1"]){
                //支付宝支付
                [self payByALiWithHandle:responseObject[@"data"][@"alSign"]];
                
            }else if ([payType isEqualToString:@"2"]){
                //微信支付
                [self weiXinpay:responseObject[@"data"]];
            }
            
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
        [self hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

//获取数据
- (void)getData{
    [self showprogressHUD];
    //商品id
    NSString *strcId = @"";
    //商品数量
    NSString *strNumber = @"";
    //设备id
    NSString *streId = self.eId;
    //总金额
    NSString *strTotal = @"";
    int money = 0;
    for (int i = 0; i < self.dataArray.count; i++) {
        strcId = [strcId stringByAppendingFormat:@"%@,",self.dataArray[i][@"g_id"]];
        strNumber = [strNumber stringByAppendingFormat:@"%@,",self.dataArray[i][@"number1"]];
        money += [self.dataArray[i][@"price"] intValue] * [self.dataArray[i][@"number1"] intValue];
    }
    strTotal = [NSString stringWithFormat:@"%d",money];
    
    //NSLog(@"111---%@ | ,%@ | ,%@ | ,%@",strcId,strNumber,streId,strTotal);
    NSDictionary *parameters = @{@"auId":[UserModel sharedInstanced].userId,
                                 @"cId":strcId,
                                 @"number":strNumber,
                                 @"eId":streId,
                                 @"total":strTotal
                                 };
    [[AFAppDotNetAPIClient sharedClient] POST:@"/wardrobe/Laundry_Order/userOrder.do" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            [self.dataArray removeAllObjects];
            [self.dataArray addObjectsFromArray:responseObject[@"obj1"]];
            //总金额
            self.moneyLabel.text = [NSString stringWithFormat:@"¥%@",responseObject[@"obj"][@"lo_total"]];
            //订单编号
            self.theOrderNumberLabel.text = responseObject[@"obj"][@"lo_number"];
            //订单号
            loId = responseObject[@"obj"][@"lo_id"];
            [self.tableView reloadData];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        [self hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

@end

//ui
@implementation RootMakeSureTheOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"确认订单";
    promptStrong = @"请输入留言内容";
    [self.view addSubview:self.tableView];
    for (NSArray *array in self.mutableDataArray) {
        if (array.count > 0) {
            [self.dataArray addObjectsFromArray:array];
        }
    }
    [self getData];
}

#pragma mark - init

- (UILabel *)theOrderNumberLabel{
    if (!_theOrderNumberLabel) {
        _theOrderNumberLabel  = [[UILabel alloc]initWithFrame:CGRectMake(100 / WIDTH_5S_SCALE, 0, SCREEN_WIDTH - 110 / WIDTH_5S_SCALE, 30 / WIDTH_5S_SCALE)];
        _theOrderNumberLabel.font = DEF_FontSize_14;
        _theOrderNumberLabel.textColor = getColor(mainColor);
        _theOrderNumberLabel.textAlignment = NSTextAlignmentRight;
        //_theOrderNumberLabel.text = @"2423431232131242";
    }
    return _theOrderNumberLabel;
}

- (UIView *)headView{
    if (!_headView) {
        _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30 / WIDTH_5S_SCALE)];
        UILabel *leftLabel  = [[UILabel alloc]initWithFrame:CGRectMake(10 / WIDTH_5S_SCALE, 0, 200, 30 / WIDTH_5S_SCALE)];
        leftLabel.font = DEF_FontSize_14;
        leftLabel.textColor = getColor(mainColor);
        NSMutableAttributedString *attStr1 = [NSMutableAttributedString new];
        NSTextAttachment *seeAtt1 = [NSTextAttachment new];
        seeAtt1.bounds = CGRectMake(0, - 2, 10 / WIDTH_5S_SCALE, 12 / WIDTH_5S_SCALE);
        seeAtt1.image = [UIImage imageNamed:@"root_TheOrderNumber"];
        [attStr1 appendAttributedString:[NSAttributedString attributedStringWithAttachment:seeAtt1]];
        [attStr1 appendAttributedString:[[NSAttributedString alloc] initWithString:@" 订单号"]];
        leftLabel.attributedText = attStr1;
        [_headView addSubview:leftLabel];
        [_headView addSubview:self.theOrderNumberLabel];
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 30 / WIDTH_5S_SCALE - 0.5, SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = getColor(dividerColor);
        [_headView addSubview:lineView];
    }
    return _headView;
}

- (UIView *)footView{
    if (!_footView) {
        _footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300 / WIDTH_5S_SCALE)];
        UILabel *allMoneyLabel  = [[UILabel alloc]initWithFrame:CGRectMake(10 / WIDTH_5S_SCALE, 0, 200 / WIDTH_5S_SCALE, 33 / WIDTH_5S_SCALE)];
        allMoneyLabel.font = DEF_FontSize_14;
        allMoneyLabel.textColor = getColor(mainColor);
        allMoneyLabel.text = @"总价";
        [_footView sd_addSubviews:@[allMoneyLabel , self.moneyLabel]];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 33 / WIDTH_5S_SCALE - 0.5, SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = getColor(dividerColor);
        [_footView addSubview:lineView];
        
        UILabel *leftLabel  = [[UILabel alloc]initWithFrame:CGRectMake(5 / WIDTH_5S_SCALE, 33 / WIDTH_5S_SCALE, 200 / WIDTH_5S_SCALE, 33 / WIDTH_5S_SCALE)];
        leftLabel.font = DEF_FontSize_14;
        leftLabel.textColor = getColor(mainColor);
        NSMutableAttributedString *attStr1 = [NSMutableAttributedString new];
        NSTextAttachment *seeAtt1 = [NSTextAttachment new];
        seeAtt1.bounds = CGRectMake(0, - 2, 10 / WIDTH_5S_SCALE, 12 / WIDTH_5S_SCALE);
        seeAtt1.image = [UIImage imageNamed:@"root_IWantToLeaveAMessage"];
        [attStr1 appendAttributedString:[NSAttributedString attributedStringWithAttachment:seeAtt1]];
        [attStr1 appendAttributedString:[[NSAttributedString alloc] initWithString:@" 我要留言"]];
        leftLabel.attributedText = attStr1;
        [_footView addSubview:leftLabel];
        
        UIView *line1View = [[UIView alloc]initWithFrame:CGRectMake(0, 66 / WIDTH_5S_SCALE - 0.5, SCREEN_WIDTH, 0.5)];
        line1View.backgroundColor = getColor(dividerColor);
        [_footView addSubview:line1View];
        [_footView addSubview:self.textView];
        
        UIView *line2View = [[UIView alloc]initWithFrame:CGRectMake(0, 66 / WIDTH_5S_SCALE  + 1 + 5 / WIDTH_5S_SCALE + 69 / WIDTH_5S_SCALE, SCREEN_WIDTH, 0.5)];
        line2View.backgroundColor = getColor(dividerColor);
        [_footView addSubview:line2View];
        [_footView addSubview:self.paymentButton];
    }
    return _footView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionFooterHeight = .01;
        _tableView.sectionHeaderHeight = .01;
        _tableView.tableFooterView = self.footView;
        _tableView.tableHeaderView = self.headView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.backgroundColor = getColor(@"ffffff");
    }
    return _tableView;
}

- (UITextView *)textView{
    if (!_textView) {
        _textView  = [[UITextView alloc]initWithFrame:CGRectMake(10 / WIDTH_5S_SCALE, 66 / WIDTH_5S_SCALE + 1 + 5 / WIDTH_5S_SCALE, SCREEN_WIDTH - 20 / WIDTH_5S_SCALE, 69 / WIDTH_5S_SCALE)];
        _textView.font = DEF_FontSize_14;
        _textView.textColor = getColor(@"999999");
        _textView.delegate = self;
        _textView.text = promptStrong;
    }
    return _textView;
}

- (UILabel *)moneyLabel{
    if (!_moneyLabel) {
        _moneyLabel  = [[UILabel alloc]initWithFrame:CGRectMake(100 / WIDTH_5S_SCALE, 0, SCREEN_WIDTH - 110 / WIDTH_5S_SCALE, 33 / WIDTH_5S_SCALE)];
        _moneyLabel.font = DEF_FontSize_14;
        _moneyLabel.textColor = getColor(mainColor);
        _moneyLabel.text = [NSString stringWithFormat:@"¥%@",@"0.00"];
        _moneyLabel.textAlignment = NSTextAlignmentRight;
    }
    return _moneyLabel;
}

- (UIButton *)paymentButton{
    if (!_paymentButton) {
        _paymentButton = [[UIButton alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - 106 / WIDTH_5S_SCALE) / 2, 66 / WIDTH_5S_SCALE  + 1 + 5 / WIDTH_5S_SCALE + 69 / WIDTH_5S_SCALE + 50 / WIDTH_5S_SCALE, 106 / WIDTH_5S_SCALE, 22 / WIDTH_5S_SCALE)];
        _paymentButton.titleLabel.font = DEF_FontSize_14;
        _paymentButton.layer.masksToBounds = YES;
        _paymentButton.layer.cornerRadius = 11 / WIDTH_5S_SCALE;
        [_paymentButton setTitle:@"付款" forState:UIControlStateNormal];
        [_paymentButton setTitleColor:getColor(@"ffffff") forState:UIControlStateNormal];
        _paymentButton.backgroundColor = getColor(mainColor);
        [_paymentButton addTarget:self action:@selector(paymentButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _paymentButton;
}

#pragma mark - click

- (void)paymentButtonClick{
    MethodOfPaymentView *view = [[MethodOfPaymentView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) selectedHandle:^(NSString *str) {
        //支付方式 0-会员卡支付,1-支付宝支付,2-微信支付
        payType = str;
        switch ([str integerValue]) {
            case 0:
            {
                NSLog(@"会员卡支付");
                if ([[UserModel sharedInstanced].payThePassword isEqualToString:@""]) {
                    ShowMessage(@"请先设置支付密码");
                    return ;
                }
                TheMembershipCardToPayView *view = [[TheMembershipCardToPayView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) selectedHandle:^(NSString * str){
                    NSLog(@"输入密码%@",str);
                    //判断密码输入是否正确
                    if ([[UserModel sharedInstanced].payThePassword isEqualToString:str]) {
                        [self payOrder];
                        //会员卡充值,余额不足情况下
                        /*
                        LackOfBalanceView *view = [[LackOfBalanceView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) selectedHandle:^{
                            NSLog(@"余额不足");
                            MemberPrepaidPhoneViewController *vc = [MemberPrepaidPhoneViewController new];
                            [self.navigationController pushViewController:vc animated:YES];
                        }];
                        [view show];
                         */
                        
                    }else{
                        ShowMessage(@"密码输入错误");
                        return ;
                    }
                }];
                [view show];
                break;
            }
            case 1:
            {
                NSLog(@"支付宝支付");
                [self payOrder];
                break;
            }
            case 2:
            {
                NSLog(@"微信支付");
                [self payOrder];
                break;
            }
        }
    }];
    [view show];
}

#pragma mark - <UITableViewDelegate , UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RootMakeSureTheOrderTableViewCell *cell = [RootMakeSureTheOrderTableViewCell cellForTableView:tableView];
    cell.model = self.dataArray[indexPath.row];
    //cell.accessoryType = indexPath.row == 3 ?  UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45 / WIDTH_5S_SCALE;
}

#pragma mark - UITextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:promptStrong]) {
        textView.text = @"";
        textView.textColor = getColor(textColor);
    }
    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.text = promptStrong;
        textView.textColor = getColor(@"999999");
    }
    return YES;
}


#pragma mark - Event

/**
 支付宝支付
 
 @param orderString orderString description
 */
- (void)payByALiWithHandle:(NSString *)orderString{
    //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
    NSString *appScheme = @"xiyialisdkdemo";
    // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        
        if ([resultDic[@"resultStatus"] isEqualToString:@"6001"]) {
            ShowMessage(resultDic[@"memo"]);
        }
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            [self.view makeToast:@"支付成功!" duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }
    }];
}

/**
 微信支付
 */
- (void)weiXinpay:(NSDictionary *)dic{
    PayReq *request = [[PayReq alloc]init];
    request.partnerId = dic[@"partnerid"];
    request.prepayId= dic[@"prepayid"];
    request.package = dic[@"package"];
    request.nonceStr= dic[@"noncestr"];
    request.timeStamp= [dic[@"timestamp"] intValue];
    request.sign= dic[@"sign"];
    [WXApi sendReq:request];
}

//通知执行事件
/**
 微信支付成功
 */
- (void)WeChatPaySuccess{
    [self.view makeToast:@"支付成功!" duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
}
/**
 微信支付用户中途取消
 */
- (void)WeChatForCancellation{
    ShowMessage(@"用户中途取消");
}
/**
 微信支付用户支付失败
 */
- (void)WeChatPaymentFailure{
    ShowMessage(@"支付失败");
}

#pragma mark - data

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray  = @[
                        ].mutableCopy;
    }
    return _dataArray;
}


@end
